package com.yourannet.utils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class FileUtils {
	
	/**
	 *  http://blog.csdn.net/peijiangping1989/article/details/7702807
	 *  //下载路径
	 	File file = new File(filepath);  
        long size = 0;  
        if (file.exists()) {  
        	//已经下载，尚未下载完毕，获取已下载内容大小
            size = file.length();  
        }  
        //文件的网络地址
        String downloadurl = "http://bs.baidu.com/appstore/apk_d9dba036522d0c2d71a77bc121b62d0b.apk";  
        //下载文件
        int value = HttpConnent.doDownloadTheFile_test(downloadurl,  
                Contants.sdCardPath + "/" + id, id + mode, 1, size,  
                handler);  
        if (value == 1) {  
            System.out.println("下载OK");  
        } else {  
            System.out.println("下载失败");  
        }  
	 */
	/**
	 * 断点续传，下载文件
	 * @param strPath 文件网络url
	 * @param filePath 文件下载路径
	 * @param filename 文件名称
	 * @param mode 网络模式
	 * @param size 文件大小
	 * @param handler 
	 * @return
	 */
	public static int doDownloadTheFilet(String strPath, String filePath,  
            String filename, int mode, long size, Handler handler) {  
        //file.size()即可得到原来下载文件的大小  
        //要下载的文件的网络URL
        String url = strPath;  
        // 设置代理  
        Header header = null;  
       /* if (mode == 2) {  
            //移动内网的时候使用代理  
            url = format_CMWAP_URL(strPath);  
            header = new BasicHeader("X-Online-Host",  
                    format_CMWAP_ServerName(strPath));  
        }*/  
        HttpResponse response = null;  
        // 用来获取下载文件的大小  
        HttpResponse response_test = null;  
        try {  
            HttpClient client = new DefaultHttpClient();  
            HttpClient client_test = new DefaultHttpClient();  
            HttpGet request = new HttpGet(url);  
            HttpGet request_test = new HttpGet(url);  
            if (header != null) {  
                request.addHeader(header);  
            }  
            response_test = client_test.execute(request_test);  
            //获取需要下载文件的大小  
            long fileSize = response_test.getEntity().getContentLength();  
            // 验证下载文件的完整性  
            if (fileSize != 0 && fileSize == size) {  
                return 1;  
            }  
            //设置下载的数据位置XX字节到XX字节  
            Header header_size = new BasicHeader("Range", "bytes=" + size + "-"  
                    + fileSize);  
            request.addHeader(header_size);  
            response = client.execute(request);  
            InputStream is = response.getEntity().getContent();  
            if (is == null) {  
                throw new RuntimeException("stream is null");  
            }  
            //SDCardUtil.createFolder(filePath);  
            //获取文件对象，开始往文件里面写内容  
            File myTempFile = new File(filePath + "/" + filename);  
            RandomAccessFile fos = new RandomAccessFile(myTempFile, "rw");  
            //从文件的size以后的位置开始写入，其实也不用，直接往后写就可以。有时候多线程下载需要用  
            fos.seek(size);  
            byte buf[] = new byte[1024];  
            long downloadfilesize = 0;  
            do {  
                int numread = is.read(buf);  
                if (numread <= 0) {  
                    break;  
                }  
                fos.write(buf, 0, numread);  
                if (handler != null) {  
                    Message msg = new Message();  
                    downloadfilesize += numread;  
                    double percent = (double) (downloadfilesize + size)  
                            / fileSize;  
                    msg.obj = String.valueOf(percent);  
                    handler.sendMessage(msg);// 更新下载进度百分比  
                }  
            } while (true);  
            is.close();  
        } catch (Exception ex) {  
            ex.printStackTrace();  
            return -1;  
        }  
        return 1;  
    }  


	/**
	 * 在SD卡中创建文件
	 * @param filePath 文件路径
	 * @param fileName 文件名
	 * @return
	 */
	public static int CreateFileInSDCard(String directory,String fileName){
		if(SDCardUtils.isExistSDCard()){
			File dir = new File(directory);
			if(!dir.exists()){
				dir.mkdirs();
			}
			File file = new File(directory, fileName);
			if(!file.exists()){
				try {
					file.createNewFile();
					return 0;
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					return -1;
				}
			}else{
				return 0;
			}						
		}else{
			//SD卡不存在
			return 1;
		}
	}
	
	/**
	 * 将字符串写入到文本文件中
	 * @param strcontent 内容
	 * @param strFilePath 文件路径
	 */
    public static void WriteTxtFile(String strcontent,String strFilePath)
    {
      //每次写入时，都换行写
      String strContent=strcontent+"\n";
      try {
           File file = new File(strFilePath);
           if (!file.exists()) {
            file.createNewFile();
           }
           RandomAccessFile raf = new RandomAccessFile(file, "rw");
           raf.seek(file.length());
           raf.write(strContent.getBytes());
           raf.close();
      } catch (Exception e) {
    	  e.printStackTrace();
      }
    }
    
    /**
	 * 生成随机字符串
	 * @int 生成随机字符串的长度
	 * @return
	 */
	public static String generateRandom(int length){
		StringBuffer buf = new StringBuffer("a,b,c,d,e,f,g,h,i,g,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z");
		buf.append(",A,B,C,D,E,F,G,H,I,G,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z");
		//buf.append(",~,@,#,$,%,^,&,*,(,),_,+,|,`,.");
		buf.append(",1,2,3,4,5,6,7,8,9,0");

		String[] arr = buf.toString().split(",");
		
		StringBuffer b = new StringBuffer();
		java.util.Random r;
		int k ;
		for(int i=0;i<length;i++){
			 r = new java.util.Random();
			 k = r.nextInt();
			 b.append(String.valueOf(arr[Math.abs(k % 61)]));
		}
		return b.toString();
	}
}
